package PostLink;

//import com.alibaba.fastjson.JSONObject;

import org.apache.commons.io.FileUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;

public class PostTest {

    /**
     * 模拟Post请求，进行url测试
     */
    public static String sendPostRequest(String content) throws IOException {
        String url = "http://10.10.10.119:33321/re/api/foobar";
        //http://10.10.10.119:33321/
//        String url = "http://127.0.0.1:12321/re/api/foobar";
        //请求ti
        JSONObject parammap = new JSONObject(content);
        return doPost(url, parammap.toString());
    }

    public static String doPost(String url, String json) {
        //创建httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String res = "";

        try {
            // 创建 httppost请求
            HttpPost post = new HttpPost(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            post.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(post);

            res = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return res;
    }

}

